package com.lsl.gulimall.product.service.impl;

import com.lsl.gulimall.product.entity.CategoryBrandRelationEntity;
import com.lsl.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.common.utils.PageUtils;
import com.lsl.common.utils.Query;

import com.lsl.gulimall.product.dao.BrandDao;
import com.lsl.gulimall.product.entity.BrandEntity;
import com.lsl.gulimall.product.service.BrandService;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByKey(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        Long brandId = brand.getBrandId();
        QueryWrapper<CategoryBrandRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id", brandId);
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities = categoryBrandRelationService.getCategoryByBrandId(brandId);
        if (categoryBrandRelationEntities != null && categoryBrandRelationEntities.size() > 0) {
            categoryBrandRelationEntities.stream().map(
                    (item) -> {
                        item.setBrandName(brand.getName());
                        return item;
                    }
            ).collect(Collectors.toList());
            categoryBrandRelationService.updateBatchById(categoryBrandRelationEntities);
        }
        this.baseMapper.updateById(brand);
    }
}